package com.aierkeji.call.cms.interceptor;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.aierkeji.call.cms.util.GsonUtils;
import com.aierkeji.call.cms.util.ResultMapHelper;

@Aspect
@Component
public class ControllerLogInterceptor {

	private final Logger log = LogManager.getLogger(getClass());

	@Pointcut("execution(public *  com.aierkeji.call.cms.controller.*.*(..))") // 两个..代表所有子目录，最后括号里的两个..代表所有参数
	public void logPointCut() {
		
	}


	@Around("logPointCut()")
	public Object Interceptor(ProceedingJoinPoint pjp) {
		long beginTime = System.currentTimeMillis();
		
		String reqId = UUID.randomUUID().toString().replaceAll("-", "");
		
		MethodSignature signature = (MethodSignature) pjp.getSignature();
		Method method = signature.getMethod(); // 获取被拦截的方法
		String methodName = method.getName(); // 获取被拦截的方法名
		Object[] args = pjp.getArgs();
		
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		// 记录下请求内容
		log.info(reqId+" 开始进入请求 : " + request.getRequestURL().toString());
		if(!request.getMethod().equalsIgnoreCase("get")){
//			log.info(reqId+" 请求数据为（已转JSON）："+ GsonUtils.parseToJson(args));
		}
		Object result = null;
//		Object resultcopy = null;
		try {
			result = pjp.proceed();
//			resultcopy = BeanUtils.cloneBean(result);
		} catch (UnauthorizedException e){
			result = ResultMapHelper.permissionDenied();
		} catch (AuthorizationException e){
			result = ResultMapHelper.permissionDenied();
		} catch (Throwable e) {
			log.error("exception:", e);
			result = ResultMapHelper.failure("发生未知异常："+e.getMessage());
		}
		if(result instanceof Map) {
			String responseData = StringEscapeUtils.unescapeXml(GsonUtils.parseToJson(result));
			log.info(reqId+" 请求返回数据为："+responseData);
		}
		long costMs = System.currentTimeMillis() - beginTime;
		if((costMs/1000) > 5){
			log.info(reqId+" 请求 over 5 minis....");
		}
		log.info(reqId+" {}请求结束，耗时：{}ms", methodName, costMs);

		return result;
	}
}
